import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'
import './assets/css/global.css'
import './assets/iconfont/iconfont.css'

import { Loading, Message, MessageBox } from 'element-ui'

import axios from 'axios'


// 挂载属性到 Vue.prototype
Vue.prototype.$http = axios;
Vue.prototype.$elementLoading = Loading;
Vue.prototype.$elementMessage = Message;
Vue.prototype.$elementMessageBox = MessageBox;

// 超时时间
axios.defaults.timeout = 30000;
// 懒加载
var loadinginstace = null;

let reqNum = 0;

function closeLoading() {
    reqNum--;
    if (reqNum <= 0) {
        setTimeout(() => {
            try {
                loadinginstace.close();
                loadinginstace = null;
            } catch (error) {

            }
        }, 200);
    }
}

// 全局请求拦截
axios.interceptors.request.use(config => {
    const token = window.sessionStorage.getItem("Authorization");
    // 请求头添加token
    config.headers.Authorization = token;
    var path = config.url.split("/").pop();
    if (path === "list") {
        reqNum++;
        loadinginstace = Loading.service({ fullscreen: true });
    }
    return config
}, error => {
    closeLoading();
    Message.error({
        message: '网络不给力,请稍后再试'
    });
    return Promise.reject(error)
});
// 全局响应拦截
axios.interceptors.response.use(data => {
    closeLoading();
    const code = data.data.code;
    if (code == 401) {
        MessageBox.alert('请登录', '提示', {
            confirmButtonText: '确定',
            callback: () => {
                router.push("/login");
            }
        });
        return;
    }
    if (code !== 200) {
        Message.error({
            message: data.data.message,
        });
    }
    return data;
}, error => {
    closeLoading();
    Message.error({
        message: '网络不给力,请稍后再试'
    });
    return Promise.reject(error);
});

// axios.defaults.baseURL = "http://localhost:8081/api";

 axios.defaults.baseURL = "http://119.3.13.191:8081/api";

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')